package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前登录的用户
        //Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        //从session获取登录用户
        Employee employee = UserContext.getCurrentEmployee();

        //判断是否管理员，
        if (employee.isAdmin()) {//是管理员
            return true;
        }

        // 若不是管理员，获取当前要执行的控制器的处理方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 判断 method 中是否贴了权限注解 @RequiredPermission
        RequiredPermission annotation =
                handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if (annotation == null) {
            // 若没有贴自定义权限注解，直接放行
            return true;
        }



        //贴了自定义权限注解
        //获取方法上的权限表达式
        String expression = annotation.expression();
        //获取当前用户所有权限表达式,根据员工id数据库查询所拥有权限表达式,替换不再去数据库区查询
        //List<String> expressions = permissionService.queryByEmployeeId(employee.getId());
        //从session中获取权限数据
        //List<String> expressions = (List<String>)request.getSession().getAttribute("EXPRESSION_IN_SESSION");

        List<String> expressions=UserContext.getExpressions();

        //用户具有访问权限
        if (expressions.contains(expression)) {
            return true;//放行
        }
        //走到这里,用户不具备权限
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp")
                .forward(request,response);

        return false;

    }
}
